import type { Request, Response } from "express";
import { decoded } from "./jwt";
import { pathToRegexp } from "path-to-regexp";
import { ResponseCode } from "./utils/ResponseHelper";

const whiteList = [
  // { method: "POST", path: "(.*)/boss/login" },
  { method: "POST", path: "(.*)/users/login" },
  { method: "POST", path: "(.*)/users/register" },
  { method: "POST", path: "(.*)/email/code" },
  { method: "GET", path: "(.*)/markers/findById(.*)" },
  { method: "GET", path: "(.*)/journals/findOpenJournal(.*)" },
  { method: "PUT", path: "(.*)/users/modifyPassword" }, // 修改密码
  { method: "POST", path: "(.*)/email/modifyPassword/code" }, // 修改密码的验证码
  // { method: "GET", path: "(.*)/class(.*)" },
  // { method: "GET", path: "(.*)/article/findByPage(.*)" },
  // { method: "GET", path: "(.*)/article/articleContent(.*)" },
];

export default (req: ITokenRequest, res: Response, next) => {
  const apis = whiteList.filter((api) => {
    const reg = pathToRegexp(api.path);

    return api.method === req.method && reg.test(req.path);
  });

  // 判断请求的接口是否 不需要 token 认证
  if (apis.length !== 0) {
    next();
    return;
  }

  // 判断token 是否正确
  const result = decoded(req);
  if (result) {
    req.UID = result["id"] || ""; // 班级id,仅 用户有
    req.EMAIL = result["email"] || ""; // 用户id
    next();
  } else {
    handleNonToken(res);
  }
};

// 处理没有认证的情况
function handleNonToken(res: Response) {
  res.send({
    code: ResponseCode.NOT_ALLOW,
    data: {},
    msg: "you don't have any token to access the api",
  });
}

export interface ITokenRequest extends Request {
  UID: number;
  EMAIL: string;
}
